package com.ktjiaoyu.utils;

import com.alibaba.fastjson2.filter.ValueFilter;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Set;

/**
 * @author 黄军艳
 * @version 1.0
 * @date 2024/12/21  10:24
 */
public class FastJson2DateValueFilter implements ValueFilter {
    // 定义参考如下格式
// {
// "(?i)^.*(day|date)$" : "yyyy-MM-dd",
// "(?i)^.*(time)$" : "yyyy-MM-dd HH:mm:ss",
// "(?i)^.*(datetime)$" : "HH:mm:ss"
// }
    private LinkedHashMap<String, String> dateMappings = null;
    public FastJson2DateValueFilter(
            LinkedHashMap<String, String> dateMappings) {
        this.dateMappings = dateMappings;
    }
    @Override
    public Object apply(Object object, String propertyName, Object value) {
        if (dateMappings == null) {
            return value;
        }
// 要判断数据类型,只处理 Date 类型
        if (value instanceof Date) {
            Set<String> keySet = dateMappings.keySet();
            for (String pattern : keySet) {
// 循环所有的正则表达式，判断属性名是否符合正则要求
                if (propertyName.matches(pattern)) {
// 符合要求的取出格式进行转换
                    String dateFormat = dateMappings.get(pattern);
// 返回对应格式
                    SimpleDateFormat formatter = new
                            SimpleDateFormat(dateFormat);
                    return formatter.format((Date) value);
                }
            }
        }
        return value;
    }
}
